<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">  <!-- 设置字符编码为 UTF-8 -->
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>内容社区</title>
    <link rel="icon" href="/img/favicon.png" type="image/png">
    <script src="libs/axios.min.js"></script>
    <script src="libs/vue.global.js"></script>
    <script src="libs/index.full.js"></script>
    <script src="libs/index.iife.js"></script>
    <script src="js/navbar.js"></script>
    <link rel="stylesheet" href="libs/index.css">
    <link rel="stylesheet" href="css/navbar.css">
    <link rel="stylesheet" href="css/community.css">
</head>
<body>
<div id="app" class="full_container">
    <div id="navbar" class="navbar"></div>
    <div class="community_container">
        <div class="container-left">
            <div class=container-left-list>
                <div class="container-left-list-item">
                    <img class="container-left-list-item-icon" src="img/发现.png">
                    <p class="container-left-list-item-text">发现</p>
                </div>
                <div class="container-left-list-item">
                    <img class="container-left-list-item-icon" src="img/发布.png">
                    <p class="container-left-list-item-text" @click="open">发布</p>
                </div>
                <div class="container-left-list-item">
                    <img class="container-left-list-item-icon" src="img/通知.png">
                    <p class="container-left-list-item-text">通知</p>
                </div>
                <div class="container-left-list-item">
                    <img class="container-left-list-item-icon" src="img/礼物.png">
                    <p class="container-left-list-item-text">我的</p>
                </div>
            </div>
            <div class="container-left-more">
                <img class="container-left-more-icon" src="img/更多.png">
                <p class="container-left-more-text">更多</p>
            </div>
        </div>
        <div class="container-right"
             v-infinite-scroll="load"
             infinite-scroll-disabled="loading"
             infinite-scroll-distance="10">
            <div class="container-right-item" v-for="(post, index) in posts" :key="post.id" @click="openDialog(post)">
                <img class="container-right-item-img" :src="post.image[0]">
                <div class="container-right-item-footer">
                    <div class="container-right-item-footer-text">{{post.title}}</div>
                    <div class="introduce">
                        <div class="author">
                            <img class="author-icon" :src="post.avatar">
                            <div class="author-text">{{post.nickname}}</div>
                        </div>
                        <div class="like">
                            <img class="like-icon" src="/img/喜欢.png">
                            <div class="like-text">{{i}}</div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
    <el-dialog v-model="dialogVisible" class="post-dialog">
        <div class="dialog_left">
            <el-carousel class="dialog_carousel" trigger="click" height="100%">
                <el-carousel-item class="carousel_item" v-for="(image, index) in images" :key="index">
                    <img class="carousel_item-img" :src="image" alt="轮播图片" @click="openLink(index)">
                </el-carousel-item>
            </el-carousel>
        </div>
        <div class="dialog_right">
            <div class="dialog_author">
                <img class="dialog_author-avatar" :src="selectedPost.avatar">
                <div class="dialog_author-text">{{selectedPost.nickname}}</div>
            </div>
            <div class="dialog_content">
                <div class="dialog_content-text">{{selectedPost.content}}</div>
                <div class="dialog_content-footer">
                    <div class="dialog_content-datetime">{{selectedPost.createdAt}} {{selectedPost.region}}</div>
                    <div class="dialog_content-area"></div>
                    <div class="dialog_content-like" @click="collect">收藏</div>
                </div>
            </div>
            <div class="dialog_comments">
                <div class="dialog_comments_item" v-for="(comment, index) in comments" :key="index">
                    <div class="dialog_comments-main">
                        <img class="dialog__comment-avatar--main" :src="comment.avatar">
                        <div class="dialog_comments-text--main">{{comment.content}}</div>
                    </div>
                    <div v-if="isExpand[comment.id]" class="dialog__comment-footer"
                         v-for="(subComment, index) in subComments" :key="index">
                        <img class="dialog_comments-avatar--footer" :src="subComment.avatar">
                        <div class="dialog_comments-text--footer">{{subComment.content}}</div>
                    </div>
                    <div v-if="!isExpand[comment.id]" @click="Expand(comment)">点击展开回复</div>
                    <div v-if="isExpand[comment.id]" @click="Expand(comment)">点击收回回复</div>
                </div>
            </div>
            <div class="dialog_input">
                <el-input v-model="input" @keyup.enter="handleSubmit"></el-input>
            </div>
        </div>
    </el-dialog>
    <el-dialog
            title="发布新内容"
            v-model="dialogVisible2"
            width="50%"
            @close="resetForm"
            class="community_dialog"
    >
        <el-form :model="formData" ref="formRef" label-width="80px">
            <el-form-item label="标题" prop="title"
                          :rules="[{ required: true, message: '请输入标题', trigger: 'blur' }]">
                <el-input v-model="formData.title" placeholder="请输入标题"></el-input>
            </el-form-item>

            <el-form-item label="内容" prop="content"
                          :rules="[{ required: true, message: '请输入内容', trigger: 'blur' }]">
                <el-input type="textarea" v-model="formData.content" placeholder="请输入内容" :rows="4"></el-input>
            </el-form-item>

            <el-form-item label="发布地" prop="region"
                          :rules="[{ required: true, message: '请输入发布地', trigger: 'blur' }]">
                <el-input v-model="formData.region" placeholder="请输入发布地"></el-input>
            </el-form-item>

            <el-form-item label="上传图片" prop="image"
                          :rules="[{ required: true, message: '请上传图片', trigger: 'change' }]">
                <el-upload
                        class="upload-demo"
                        action="/community/upload"
                        :on-change="handleFileChange"
                        :before-upload="beforeUpload"
                        :file-list="fileList"
                        accept="image/*"
                        list-type="picture-card"
                >
                    <el-icon>
                        <Plus/>
                    </el-icon>
                </el-upload>
            </el-form-item>
        </el-form>

        <!-- 弹框底部按钮 -->
        <div class="dialog-footer">
            <el-button @click="dialogVisible2 = false">取消</el-button>
            <el-button type="primary" @click="submitForm">提交</el-button>
        </div>
    </el-dialog>
</div>
<script>
    const {createApp} = Vue;

    const {ElMessage} = ElementPlus;

    const app = createApp({
        data() {
            return {
                count: 0, // 初始内容数量
                loading: false, // 加载状态
                posts: [],
                dialogVisible: false, // 控制弹框显示
                selectedPost: {}, // 当前选中的帖子
                postId: 0, // 选中帖子的id
                images: [], // 用于弹框中显示图片的数组
                comments: [],
                commentId: 0,//选中评论的id
                subComments: [],
                isExpand: {},
                commentCount: 0,
                input: '',
                currentUserId: 0,
                floor: 0,
                dialogVisible2: false, // 控制弹框显示
                formData: {
                    title: "",
                    content: "",
                    region: "",
                    image: "",
                },
                // 文件列表
                fileList: [],
                permissionLevel:0,
            }
        },
        mounted() {
            this.getData(); // 组件挂载时获取数据
            this.getCurrentUser();
        },
        methods: {
            // 加载更多内容的函数
            load() {
                if (this.loading) return; // 防止重复加载
                this.loading = true;

                setTimeout(() => {
                    this.count += 8; // 每次加载 8 个内容项
                    this.loading = false;
                }, 500); // 模拟请求延迟
            },
            convertTimestampToMonthDay(timestamp) {
                const date = new Date(timestamp);
                const month = date.getMonth() + 1; // 月份从 0 开始，所以加 1
                const day = date.getDate();
                return `${month}-${day}`; // 格式：月-日
            },
            getData() {
                axios.get('http://localhost:8080/community/getList')
                    .then(response => {
                        this.posts = response.data.data.map(post => {
                            post.createdAt = this.convertTimestampToMonthDay(post.createdAt);
                            if (post.image) {
                                post.image = JSON.parse(post.image);  // 将字符串解析为数组
                            }
                            return post;
                        });
                        const urlParams = new URLSearchParams(window.location.search);
                        const id = urlParams.get('id');
                        const showDialog = urlParams.get('showDialog');

                        if (showDialog === 'true' && id) {
                            this.selectedPost = this.posts[id-1]; // 保存选中的帖子数据
                            this.dialogVisible = true;
                            this.postId = this.selectedPost.id;
                            this.images = this.selectedPost.image; // 设置图片数组
                            this.dialogVisible = true; // 显示弹框
                            this.getMainCommentsData(this.selectedPost);
                            this.getSubCommentsData();
                        }
                    })
                    .catch(error => {
                        console.error("请求失败:", error);
                    })
            },
            getMainCommentsData() {
                axios.get(`http://localhost:8080/comments/main/${this.postId}`)
                    .then(response => {
                        this.comments = response.data.data.map(comment => {
                            comment.createdAt = this.convertTimestampToMonthDay(comment.createdAt);
                            return comment;
                        });
                        this.floor = response.data.data.length + 1;
                    })
                    .catch(error => {
                        console.error("请求失败:", error);
                    })
            },
            getSubCommentsData() {
                if (this.isExpand[this.commentId]) {
                    axios.get(`http://localhost:8080/comments/sub/${this.postId}/${this.commentId}`)
                        .then(response => {
                            this.subComments = response.data.data.map(subComment => {
                                subComment.createdAt = this.convertTimestampToMonthDay(subComment.createdAt);
                                return subComment;
                            });
                            this.commentCount = response.data.data.length;
                        })
                        .catch(error => {
                            console.error("请求失败:", error);
                        })
                } else {
                    axios.get(`http://localhost:8080/comments/subOne/${this.postId}/${this.commentId}`)
                        .then(response => {
                            this.subComments = response.data.data.map(subComment => {
                                subComment.createdAt = this.convertTimestampToMonthDay(subComment.createdAt);
                                return subComment;
                            });

                        })
                        .catch(error => {
                            console.error("请求失败:", error);
                        })
                }

            },
            // 打开弹框
            openDialog(post) {
                this.selectedPost = post; // 保存选中的帖子数据
                this.postId = post.id;
                this.images = post.image; // 设置图片数组
                this.dialogVisible = true; // 显示弹框
                this.getMainCommentsData(post);
                this.getSubCommentsData();

            },
            Expand(comment) {
                this.commentId = comment.id;
                this.isExpand[comment.id] = !this.isExpand[comment.id] || false;
                this.getSubCommentsData();
            },
            getCurrentUser() {
                axios.get('http://localhost:8080/chat/currentUser')
                    .then(response => {
                        if (response.data.code === 200) {
                            this.currentUserId = response.data.data.id;
                            this.permissionLevel = response.data.data.permissionLevel;
                            console.log(this.currentUserId)
                        } else {
                            console.warn("未登录，跳转到登录页");
                            window.location.href = "/login.html"; // 重定向到登录页
                        }
                    })
                    .catch(error => console.error("获取当前用户失败:", error));
            },
            handleSubmit() {
                if(this.permissionLevel >= 2){
                    axios.post('http://localhost:8080/comments', {
                        content: this.input,
                        userId: this.currentUserId,
                        communityId: this.postId,
                        isMain: 1,
                        floor: this.floor,
                        commentId: 0,
                    }).then(response => {
                        this.input = '';
                        ElMessage.success("评论成功");
                        this.getMainCommentsData();
                    })
                        .catch(error => {
                            console.error("请求失败:", error);
                        })
                }else {
                    ElMessage.warning("对不起，您没有权限")
                }
            },
            // 上传前的校验
            beforeUpload(file) {
                const isImage = file.type.startsWith("image/");
                if (!isImage) {
                    this.$message.error("只能上传图片文件！");
                }
                return isImage;
            },

            // 处理上传文件变更
            handleFileChange(file, fileList) {
                if (file.response && file.response.path) {
                    // 把新的图片路径加到已有列表中
                    if (!Array.isArray(this.fileList)) {
                        this.fileList = [];
                    }
                    this.fileList.push(file.response.path);
                    this.formData.image = this.fileList;
                } else {
                    // 上传失败时可以选择不变或清空
                    console.warn("图片上传失败或未返回路径");
                }

            },

            // 提交表单
            submitForm() {
                this.$refs.formRef.validate((valid) => {
                    if (valid) {
                        console.log(this.fileList)
                        axios.post('http://localhost:8080/community', {
                            title: this.formData.title,
                            content: this.formData.content,
                            image: JSON.stringify(this.fileList),
                            region:this.formData.region,
                            userId: this.currentUserId,
                            commentId: this.currentUserId,
                        }).then(response => {
                            this.resetForm();
                            ElMessage.success("添加成功");
                            this.getMainCommentsData();
                        })
                            .catch(error => {
                                console.error("请求失败:", error);
                            })
                        console.log("提交的数据：", this.formData);
                        this.dialogVisible2 = false; // 关闭弹框
                        this.getData();
                    } else {
                        console.log("表单验证失败");
                    }
                });
            },

            // 重置表单
            resetForm() {
                this.formData = {
                    title: "",
                    content: "",
                    region: "",
                    image: "",
                };
                this.fileList = [];
            },
            open() {
                if(this.permissionLevel >= 2){
                    this.dialogVisible2 = !this.dialogVisible2;
                }else {
                    ElMessage.warning("对不起，您没有权限")
                }
            },
            collect(){
                if(this.permissionLevel >= 2){
                    const createTime = new Date().toISOString();
                    const data = {
                        userId: this.currentUserId,
                        targetId: this.selectedPost.id,
                        targetType: 'post',
                        createTime: createTime,
                        url: `/community.html?id=${this.selectedPost.id}&showDialog=true`
                    };
                    axios.post(`http://localhost:8080/favorites/`, data)
                        .then(response => {
                            ElMessage.success("收藏成功");  // 显示成功消息
                            this.dialogVisible=false;
                        })
                        .catch(error => {
                            console.error("收藏失败:", error);
                        })
                }else {
                    ElMessage.warning("对不起，您没有权限")
                }

            }
        },

    });
    for (const [key, component] of Object.entries(ElementPlusIconsVue)) {
        app.component(key, component);
    }
    app.use(ElementPlus).mount("#app");


</script>
</body>
</html>